from datetime import datetime

from django import http
from django.shortcuts import render
from django.views import View


from apps.contents.utils import get_categories
from apps.goods.models import SKU, GoodsCategory, GoodsVisitCount
from apps.goods.utils import get_breadcrumb
from django.core.paginator import Paginator

from apps.orders.models import OrderGoods
from utils.response_code import RETCODE

#1.列表页
class ListView(View):
    def get(self,request, category_id, page_num):
        # 1.三级分类的显示
        categories = get_categories()
        # 2.面包屑组件
        breadcrumb = get_breadcrumb(category_id)
        # 3.列表数据 排序
        category = GoodsCategory.objects.get(id = category_id)
        sort = request.GET.get('sort')
        if sort == 'price':
            sort = 'price'
        elif sort == 'hot':
            sort = '-sales'
        else:
            sort = 'create_time'

        skus = SKU.objects.filter(category=category ,is_launched=True).order_by(sort)
        # 4.分页
        #每页的个数
        paginator = Paginator(skus, 5)
        #共几页
        total_page = paginator.num_pages
        #每页的数据
        page_skus = paginator.page(page_num)

        context = {
            'categories':categories,
            'breadcrumb':breadcrumb,
            'sort':sort,
            'category': category,  # 第三级分类
            'page_skus': page_skus,  # 分页后数据
            'total_page': total_page,  # 总页数
            'page_num': page_num  # 当前页码
        }
        return render(request, 'list.html', context)


#2.热销排行
class HotView(View):
    def get(self,request, category_id):
        skus = SKU.objects.filter(category_id = category_id, is_launched=True).order_by('-sales')[:2]
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id':sku.id,
                'name':sku.name,
                'default_image_url':sku.default_image.url,
                'price':sku.price
            })
        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'OK', 'hot_skus':hot_skus})


#3.详情页
class DetailView(View):
    """商品详情页"""

    def get(self, request, sku_id):
        """提供商品详情页"""
        # 获取当前sku的信息
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

        # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category_id)

        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options

        # 渲染页面
        context = {
            'categories':categories,
            'breadcrumb':breadcrumb,
            'sku':sku,
            'specs': goods_specs,
        }
        return render(request, 'detail.html', context)


#4.访问量
class DetailVisitView(View):
    def post(self, request, category_id):
        # 1.接受参数
        try:
            category = GoodsCategory.objects.get(id = category_id)
        except Exception as e:
            return http.HttpResponseNotFound('缺少必传参数')
        # 2.日期格式化
        date_str = datetime.now().strftime('%Y-%m-%d')
        date_today = datetime.strptime(date_str, '%Y-%m-%d')
        # 3.判断当天是否有访问记录
        try:
            visit = GoodsVisitCount.objects.get(date=date_today, category=category)
        # 4.如果没有新建
        except Exception as e:
            visit = GoodsVisitCount()

        visit.count += 1
        visit.category = category
        visit.save()
        # 5.返回
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


#5.详情页显示评论
class CommentsView(View):
    def  get(self, request, sku_id):
        # 通过sku_id从order_goods获取 goods对象
        goods = OrderGoods.objects.filter(sku_id=sku_id, is_commented=True).order_by('-update_time')
        count = goods.count()
        sku = SKU.objects.get(id = sku_id)
        sku.comments = count
        sku.save()
        spu = sku.spu
        spu.comments += sku.comments
        spu.save()
        # 用goods
        #     判断是否评论 评论展示
        comment_list = []
        for good in goods:
            order = good.order
            user = order.user
            username = user.username
            #     判断是否匿名显是
            #         是 将用户名改为 匿名用户
            if good.is_anonymous:
                username = '匿名用户'
            # 否 显示用户的用户名
            else:
                username = username[0] + '***' + username[-1]
        #         获取 评论内容
            comment = good.comment
        #获取评分
            score = good.score
            comment_list.append({
                'username':username,
                'comment':comment,
                'score':score,
                'count':count
            })

        # 返回 用户名 内容 评分
        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'OK', 'comment_list':comment_list})


